//跳转到明细页面
var gotoFaultDetailsPage, gotoFaultsCount, searchFaultSummery,gotoCarAnaFaultInfo,goLineInfo;
require(['grid', 'topBar', 'highcharts', 'date', 'zTreeCheckbox'], function () {
    var postData;
    var passParams={};
    var $topBar =$('.topBar');

    $('#top').topBar({
        left: [{
            type: 'filter-more',
            search: function () {
                search();
            },
            item: [
                {
                    text: '时间快捷',
                    name1: 'beginTime',
                    name2: 'endTime',
                    hidden:true,
                    type: 'dateLine'
                }, {
                    text: '故障等级',
                    name: 'mftGradeCode',
                    type: 'item-select',
                    data: [
                        {text: '全部', value: ''},
                        {text: '严重', value: '1',selected:true},
                        {text: '警告', value: '3'},
                        {text: '一般', value: '2'},
                        {text: '正常', value: '4'}
                    ]
                }, {
                    text: '修复状态',
                    name: 'isHandle',
                    type: 'item-select',
                    data: [
                        {text: '全部', value: ''},
                        {text: '已修复', value: '0'},
                        {text: '未修复', value: '1',selected:true}
                    ]
                }
            ]
        }
        ],
        right: [
            {
                text: '导出',
                type: 'export-btn',
                authority: '',
                item: [
                    {
                        text: 'Excel导出',
                        click: function () {
                            exportFile('Excel');
                        }
                    },
                    {
                        text: 'PDF导出',
                        click: function () {
                            exportFile('Pdf');
                        }
                    }
                ]
            }
        ]
    });
    $('body').css('overflow', 'hidden');

    $('.pm-con').height($(window).height() - $topBar.outerHeight() - 20);

    //获取左侧选择的节点信息
    function getPostData() {
        var rcx = commonFun.getTreeCheckNodeToArgs();
        if (rcx) {
            postData = $.extend(rcx, $("#top").parent().getValues());
        }
        if (!postData.beginTime||!postData.endTime) {
        	 $.messager.alert("提示", "请选择查询起止时间段", "info");
             return false;
        }
        postData = $.extend(postData, passParams);
        postData.statisType = 'CAR';
       return rcx;
    }

    function exportFile(suffix) {
        if (getPostData()) {
            var url = "/faultsCount/exportFaultsCount" + suffix + ".htm";
            $.exportFile(url, postData);
        }
    }

    function search() {
        if (getPostData()) {
            $('#grid').grid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: postData
            }).trigger("reloadGrid");

            $.ajaxExt({
                url: "/faultsCount/searchFaultsCountDataForChart.htm",
                data: postData
            }).done(function (result) {
                if (result) {
                    var series = [{
                        type: 'pie',
                        name: '故障统计',
                        data: []
                    }];
                    $.each(result, function (index, item) {
                        series[0].data.push({name: item.ecuMftName, y: item.cnt});
                    });
                    loadPieChart('#chart', '', series);
                }
                else{
                    $('#chart').parent().hide();
                }
            });
        }
    }

    //饼图
    function loadPieChart(divId, text, series) {
        $(divId).parent().show();
        $(divId).highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: text
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        format: '<b>{point.name}</b>: {y} 次'
                    },
                    showInLegend: true
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                labelFormatter: function () {
                    return this.name;
                },
                floating: false
            },
            series: series,
            credits: {
                enabled: false
            }
        });
    }

    //跳转到明细页面
    gotoFaultDetailsPage = function (ecuMftCode, lineId, carId, isHandle, mftTypeCode) {
        var data = $("#top").parent().getValues();
        data.ecuMftCode = ecuMftCode;
        data.lineIds = lineId;
        data.carIds = carId;
        data.driverIds = "";
        data.mftTypeCode = mftTypeCode;
        data.isHandle = isHandle || '';
        $.openTab('c60acb21701a4b63ba3e6d9ddd502ab0', 'gotoSearchFaultDetails', [data]);
    };

    //跳转车辆画像-车辆故障页面
    gotoCarAnaFaultInfo = function (carId,licPltNo) {
        var data = $("#top").parent().getValues();
        var param={
            "carId":carId,
            "licPltNo":licPltNo,
            "dateType":data.dateType
        };
        $.openTab('558d6b2d93654eebbc87281e36b94158', 'gotoCarAnaFaultInfo', [param]);
    };
    
    $('#grid').grid({
        showPager:false,
         url: "/faultsCount/getCarFaultsCountData.htm",
        //url: "/drivingBehavior/searchDrivingBehaviorStatistics.htm",
        colModel: [
            {name: "carId", label: "carId", hidden: true},
            {name: "mftTypeCode", label: "mftTypeCode", hidden: true},
            {name: "lineId", label: "lineId", hidden: true},
            {name: "ranking", label: "排名", sortable:true, index:"ranking", align: "right",width:40},
            {name: "licPltNo",label: '车牌号',width: 80,align: "left",formatter: function (cellvalue,options,rowObject) {
            	return "<b><a href='javascript:void(0);' onclick='gotoCarAnaFaultInfo(\"" + rowObject.carId + "\",\"" + rowObject.licPltNo + "\")' class='text-link c-blue'>" + cellvalue + "</a></b>";
            }},
            {name: "carInCd", label: "车辆编号", width: 80},
            {name: "lineName", label: "运营线路",width:80,formatter: 'customCurrency',formatoptions:{
                redbtn:true,
                css:'text-link c-blue',
                clickFn:function(rowObject,cellvalue){
                	goLineInfo(rowObject.lineId);
                }
            }},
            {name: "lineAverage", label: "线路平均值",align: "right", width: 80},
            {name: "cnt", label: "故障总数", align: "right",width:80,summaryType: "sum",sortable:true,  summaryTpl: "小计: {0}",
            	formatter:"customCurrency", formatoptions:{
                    redbtn:true,
                    css:'text-link c-blue',
                    clickFn:function(rowObject){
                    	gotoFaultDetailsPage("", "", rowObject.carId, "", rowObject.mftTypeCode);   
                    }
            }},
            {name: "rptcnt", label: "已修复(次)", align: "right",width:100,summaryType: "sum",sortable:true, summaryTpl: "小计: {0}",
            	formatter:"customCurrency", formatoptions:{
                    redbtn:true,
                    css:'text-link c-blue',
                    clickFn:function(rowObject){
                    	gotoFaultDetailsPage("", "", rowObject.carId, "0", rowObject.mftTypeCode);   
                    }
            }},
            {name: "unrptcnt", label: "未修复(次)", align: "right",width:100,summaryType: "sum",sortable:true, summaryTpl: "小计: {0}",
            	formatter:"customCurrency", formatoptions:{
                    redbtn:true,
                    css:'text-link c-blue',
                    clickFn:function(rowObject){
                    	gotoFaultDetailsPage("", "", rowObject.carId, "1", rowObject.mftTypeCode);   
                    }
            }}
        ],

        sortname: "lineName",
        grouping:true,
        groupingView: {
            groupField: ["lineName"],
            groupSummary: [true],
            groupText: ['{0}'],
            groupCollapse: true,//是否收缩行
            showSummaryOnHide: true,//收缩隐藏时是否统计行
            groupOrder: ['asc'],//分组排序方式
            groupColumnShow: [true],//是否显示分组的列
            groupSummaryPos: ['footer']
        },
        onSortCol: function (index, colindex, sortorder)
        {
            if (getPostData()) {
                //列排序事件
                postData.index = index;
                postData.sortorder = sortorder;
                $('#grid').grid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: postData
                }).trigger("reloadGrid");
            }
        },
        rowNum:-1
    });

    $('body').css('overflow', 'inherit');

    gotoFaultsCount = function(corpId, mftDiscCode,mftTypeCode){
    	passParams={"mftTypeCode": mftTypeCode,"corpId":corpId, "mftDiscCode":mftDiscCode};
        $("a[data-val='']","[name='isHandle']").click();
    	commonFun.checkAllNodes(true);
    	$("a[data-val='02']","#top").click();
    	//清除传递参数
    	passParams={"mftTypeCode": "","corpId":"", "mftDiscCode":""};
    }
    
    searchFaultSummery = function(data){
    	console.info(data);
        $("a[data-val='']","[name='mftGradeCode']").click();
        if('MFTC0001'==data.mftGradeCode){
            $("a[data-val='2']","[name='mftGradeCode']").click();
        }
        if('MFTC0002'==data.mftGradeCode){
            $("a[data-val='1']","[name='mftGradeCode']").click();
        }
        
        $("a[data-val='']","[name='isHandle']").click();
		//切换成线路
		commonFun.showLeftTree(commonFun.lineTree);
		//勾选并展开节点
		commonFun.setCheckedNodes(data.lineId);
		
		if(data.lineIds){
			commonFun.setCheckedNodes(data.lineIds);
		}
		
    	$("a[data-val='"+data.dateType+"']","#top").click();
    }
    
  //跳转到线路信息页面
    goLineInfo = function(lineId){
    	var data = {};
    	data.lineId = lineId;
    	$.openTab('4db17f8a322b4749a61eb2f8a12023ae','showLineInfo',[data]);
    }
});